package handler

import (
	"github.com/gin-gonic/gin"
	"log"
	"net/http"
	"yk/api/request"
	"yk/global"
	"yk/internal/dao"
	"yk/internal/model"
	"yk/pkg"
)

func AddBarrage(c *gin.Context) {
	var req request.AddBarrageReq
	if err := c.ShouldBind(&req); err != nil {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "验证失败",
			"data": nil,
		})
		return
	}

	var video model.Video
	dao.GetOneByFields(&model.Video{
		Id: req.VideoId,
	}, &video)
	if video.Id == 0 {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "视频不存在",
			"data": nil,
		})
		return
	}

	if !PubBarrage(video, req, c.GetUint("userId")) {
		c.JSON(http.StatusOK, gin.H{
			"code": 1000,
			"msg":  "内容违规",
			"data": nil,
		})
		return
	}
	c.JSON(http.StatusOK, gin.H{
		"code": 200,
		"msg":  "弹幕发送成功",
		"data": true,
	})

}

func PubBarrage(video model.Video, req request.AddBarrageReq, userId uint) bool {
	tx := global.DB.Begin()
	var barrage model.Barrage

	barrage = model.Barrage{

		VideoId:    req.VideoId,
		FormUserId: userId,
		Size:       req.Size,
		STime:      req.STime,
		Content:    req.Content,
		Color:      req.Color,
	}
	if !pkg.TextCensor(req.Content) {
		log.Println("内容违规")
		tx.Rollback()
		return false
	}
	if err := tx.Create(&barrage).Error; err != nil {

		tx.Rollback()
		return false
	}
	if err := tx.Updates(&model.Video{
		Id: req.VideoId,

		BarrageNum: video.BarrageNum + 1,
	}); err != nil {

		tx.Rollback()
		return false
	}
	tx.Commit()
	return true
}
